package com.example.common.security.rbac;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: springsecurity-study
 * @description: 判断权限的接口
 * @author: ChenZhiXiang
 * @create: 2019-08-01 17:18
 **/
@Component
public class RbacServiceImpl implements RbacService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 获取当前登录的用户信息
        Object principal = authentication.getPrincipal();

        boolean hasPer = false;
        if (principal instanceof UserDetails){
            String username = ((UserDetails) principal).getUsername();
            // 根据用户名去数据库查询
            // 此处模拟
            List<String> urls = new ArrayList<>();
            urls.add("/a");
            urls.add("/add");
            for (String url : urls){
                if (antPathMatcher.match(url,request.getRequestURI())){
                    hasPer = true;
                }
            }
        }
        return hasPer;
    }
}
